package org.zxp.thread.ccontainer;

import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @program: zxp-thread-test
 * @description: ${description}
 * @author: X-Pacific zhang
 * @create: 2019-05-24 12:49
 **/
public class ConcurrentLinkedQueueTest {
    public static void main(String[] args) throws InterruptedException {
        //ConcurrentLinkedQueue是一个无锁的高性能线程安全FIFO队列
        ConcurrentLinkedQueue<String> concurrentLinkedQueue = new ConcurrentLinkedQueue();
        //add 和 offer是一样的方法
        concurrentLinkedQueue.offer("1");
        //peek从队列头部取出元素不删除
        String entry = concurrentLinkedQueue.peek();
        System.out.println("取出元素：" + entry + " 剩余：" + concurrentLinkedQueue.size());
        //poll从队列头部取出元素并删除
        entry = concurrentLinkedQueue.poll();
        System.out.println("取出元素：" + entry + " 剩余：" + concurrentLinkedQueue.size());

        //测试线程安全
        ConcurrentLinkedQueue<String> concurrentLinkedQueue2 = new ConcurrentLinkedQueue();
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                concurrentLinkedQueue2.add("i");
                try {
                    Thread.sleep(20L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        Thread.sleep(1000L);
        System.out.println(concurrentLinkedQueue2.size());//结果为是线程安全的

        ArrayQueue<String> arrayQueue = new ArrayQueue<>(1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                arrayQueue.add("i");//多线程同时有可能加到同一个位置上
            }).start();
        }
        Thread.sleep(1000L);
        System.out.println(arrayQueue.size());//结果不是线程安全的 得出的结果会变化不一定是1000
    }

}
